<template>
  <div class="app-container">
    <!-- 由此页面访问外连接时，不带refer访问 -->
    <meta name="referrer" content="never" />
    <el-row>
      <aplayer ref="aplayer" :audio="audioObj" :volume="0.5" autoplay listFolded @onListAdd="startPlay"></aplayer>
    </el-row>
    <el-divider></el-divider>
    <el-row style="margin-top: 20px">
      <el-col :span="3">
        <el-row :gutter="10" class="mb8" >
          <!-- 添加按钮 -->
          <el-col :span="1.5">
            <el-button
              circle
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAddClass"
              v-hasPermi="['alarm:deviceclass:add']"
            />
          </el-col>
          <!-- 修改按钮 -->
          <el-col :span="1.5">
            <el-button
              circle
              type="warning"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdateClass"
              v-hasPermi="['alarm:deviceclass:edit']"
            />
          </el-col>
          <!-- 删除按钮 -->
          <el-col :span="1.5">
            <el-button
              circle
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="single"
              @click="handleDeleteClass"
              v-hasPermi="['alarm:deviceclass:remove']"
            />
          </el-col>
          <!-- 刷新按钮 -->
          <el-col :span="1.2">
            <el-button
              circle
              plain
              icon="el-icon-refresh"
              size="mini"
              @click="refreshClassTree"
              v-hasPermi="['alarm:deviceclass:query']"
            />
          </el-col>
        </el-row>

        <!-- 分类树 -->
        <div class="head-container">
          <el-tree
            :data="douyinClassOptions"
            :props="defaultProps"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            :highlight-current="true"
            :draggable="true"
            :allow-drop="allowDrop"
            empty-text="无分类数据"
            node-key="id"
            ref="classTree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>

      <el-col :span="21">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="作者" prop="author">
            <el-input
              v-model="queryParams.author"
              placeholder="请输入作者"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="抖音标题" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入抖音标题"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              :disabled="single"
              @click="handleAdd"
              v-hasPermi="['spider:douyin:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['spider:douyin:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              :loading="exportLoading"
              @click="handleExport"
              v-hasPermi="['spider:douyin:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :element-loading-text="loadingText" :data="douyinList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" type="index" />
          <el-table-column label="分享链接" align="center" prop="shareUrl" show-overflow-tooltip/>
          <el-table-column label="作者" align="center" prop="author" show-overflow-tooltip/>
          <el-table-column label="文案" align="center" prop="title" show-overflow-tooltip/>
          <el-table-column label="视频或图片" align="center" prop="noWatermarkUrl">
            <template slot-scope="scope">
              <el-button size="mini" type="success" plain @click="playVideoOrPhoto(scope.row)">查看</el-button>
            </template>
          </el-table-column>

          <el-table-column label="音乐" align="center" prop="musicUrl">
            <template slot-scope="scope">
              <el-button slot="reference"
                        size="mini"
                        plain
                        type="primary"
                        @click="playMusic(scope.row)"
                        v-show="scope.row.musicUrl"
              >播放</el-button>
              <div v-show="!scope.row.musicUrl">无</div>
            </template>
          </el-table-column>
          <el-table-column label="评论数量" align="center" prop="commentCount" />
          <el-table-column label="点赞数量" align="center" prop="diggCount" />
          <el-table-column label="分享数量" align="center" prop="shareCount" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['spider:douyin:edit']"
              >更新</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['spider:douyin:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    
    <!-- 添加或修改抖音解析对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分享URL" prop="shareUrl">
          <el-input v-model="form.shareUrl" type="textarea" placeholder="请输入抖音分享的URL" />
        </el-form-item>

        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改设备分类对话框 -->
    <el-dialog :title="title" :visible.sync="open2" width="400px" append-to-body>
        <el-form ref="classForm" :model="classForm" :rules="classRuels" label-width="80px">
          <el-form-item label="父级分类">
            <el-input v-model="checkTreeNodePname" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="分类名称" prop="dyClassName">
            <el-input v-model="classForm.dyClassName" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="排序顺序" prop="orderNum">
            <el-input-number v-model="classForm.orderNum" controls-position="right" :min="0" style="width:280px;"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitClassForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>

    <!-- 图片显示抽屉-->
    <el-drawer :with-header="false" :visible.sync="open3" direction="rtl" size="35%">
      <el-image :fit="fill" v-for="url in photoList" :key="url" :src="url" lazy>
          <div slot="placeholder" class="image-slot">
            加载中<span class="dot">...</span>
          </div>
        </el-image>
    </el-drawer>

  </div>
</template>

<script>
import { listDouyin, getDouyin, delDouyin, addDouyin, updateDouyin, exportDouyin } from "@/api/douyin/douyin";
import { getDouyinClass, delDouyinClass, addDouyinClass, updateDouyinClass, treeselect } from "@/api/douyin/douyinClass";
import { getDouyinPhotoListByDouyinId } from "@/api/douyin/douyinPhoto";


export default {
  name: "Douyin",
  data() {
    return {
      open2: false,
      open3: false,
      // 遮罩层
      loading: true,
      loadingText: null,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 抖音解析表格数据
      douyinList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        classId: null,
        author: null,
        title: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        shareUrl: [
          { required: true, message: "抖音分享的URL不能为空", trigger: "blur" }
        ],
      },
      classRuels: {
        dyClassName: [ { required: true, message: "分类名不能为空", trigger: "blur" } ],
        orderNum: [ { required: true, message: "显示排序不能为空", trigger: "blur" } ]
      },
      // 音乐
      audioObj: [],
      // 图片
      photoList: [],
      // 分类树
      douyinClassOptions: {},
       // 设备分类树当前选中结点
      checkTreeNode: {},
       // 当前选中节点的父节点名称
      checkTreeNodePname: null,
      // 分类表单参数
      classForm: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
    };
  },
  created() {
    this.getList();
    this.getTreeList();
  },
  methods: {
    /** 查询抖音解析列表 */
    getList() {
      this.loading = true;
      listDouyin(this.queryParams).then(response => {
        this.douyinList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        classId: null,
        shareUrl: null,
      };
      this.resetForm("form");

      this.classForm = {
        id: null,
        pid: null,
        dyClassName: null,
        orderNum: undefined
      }
      this.resetForm("classForm")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加抖音解析";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.loadingText = "更新中"
      updateDouyin(row).then(response => {
        this.msgSuccess("更新成功");
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDouyin(this.form).then(response => {
              this.msgSuccess("更新成功");
              this.getList();
            });
          } else {
            //表格的分类ID为当前所点击的分类ID
            console.log(this.checkTreeNode.id);
            this.form.classId = this.checkTreeNode.id;
            this.open = false;
            this.loading = true;
            this.loadingText = "解析中"
            addDouyin(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除作者为"' + this.buildDelName(ids) + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDouyin(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 拼接要删除的名字 */
    buildDelName(ids){
      let s = "";
      if(typeof ids == 'string'){
        let obj = this.douyinList.find(item => {
          return item.id == ids;
        })
        if(obj){
          s = obj.author;
        }
        return "【" + s + "】";
      }
      for(let id of ids){
        let obj = this.douyinList.find(item => {
          return item.id == id;
        })
        if(obj){
          s += obj.author + ", ";
        }
      }
      return "【" + s.substring(0,s.length-2) + "】";
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有抖音解析数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportDouyin(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    /** 播放音乐 */
    playMusic(row){
      this.audioObj = [];
      this.audioObj.push({
        name: row.musicTitle,
        artist: '未知',
        url: row.musicUrl,
        cover: 'https://github.com/u3u.png',
      });
    },
    startPlay(){
      this.$refs.aplayer.play();
    },
    /** 播放视频或者图片 */
    playVideoOrPhoto(row){
      if(row.noWatermarkUrl){
        window.open(row.noWatermarkUrl);
      }else{
        this.photoList = [];
        this.open3 = true;
        // 获取抖音照片
        getDouyinPhotoListByDouyinId(row.id).then(response => {
          this.photoList = response.data;
        })
      }
    },
    /** 获取抖音分类树 */
    getTreeList(){
      treeselect().then(response => {
        this.douyinClassOptions = response.data;
        this.single = true;
        this.checkTreeNode.id = null;
      })
    },
    /** 添加分类 */
    handleAddClass(){
      this.reset();
      if(!this.checkTreeNode.id){
        this.classForm.pid = 0;
        this.checkTreeNodePname = "主分类";
        this.title = "添加分类信息"
      }else{
        this.checkTreeNodePname = this.checkTreeNode.name;
        this.classForm.pid = this.checkTreeNode.id
        this.title = "添加分类信息"
      }
      this.this.checkTreeNode.childrenNum
      this.open2 = true
    },
    /** 修改分类信息 */
    handleUpdateClass(){
      this.reset();
      getDouyinClass(this.checkTreeNode.id).then(response => {
        this.classForm = response.data;
        this.getClassTreePname(this.classForm.id);
        this.open2 = true
        this.title = "修改"+ this.checkTreeNode.name +"分类信息"
      });
    },
    /** 根据ID获取设备分类数父节点NAME */
    getClassTreePname(id){
      var node = this.$refs.classTree.getNode(id);
      if(node.parent.key != undefined)
        this.checkTreeNodePname = node.parent.data.label;
      else
        this.checkTreeNodePname = "主分类";
    },
    /** 删除分类信息 */
    handleDeleteClass(){
      const id = this.checkTreeNode.id;
      this.$confirm('是否确认删除名为"' + this.checkTreeNode.name + '"的分类?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDouyinClass(id);
        }).then(response => {
          this.checkTreeNode.id = null;
          this.checkTreeNode.name = null;
          this.getTreeList();
          this.msgSuccess(response.msg);
        }).catch(() => {});
    },
    /** 筛选节点 */
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 节点单击事件 */
    handleNodeClick(data,node) {
      //设置树和表上方按钮可操作
      this.single = false;
      //保存当前结点的ID、name和pid
      this.checkTreeNode.id = data.id;
      this.checkTreeNode.name = data.label;
      this.checkTreeNode.pid = node.parent.id;
      console.log(node);
      this.checkTreeNode.childrenNum = node.childNodes.length;
      //设置查询条件，查询属于当前分类结点的设备
      this.queryParams.classId = data.id;
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 5;
      this.getList();
    },
    /** 节点拖拽 */
    allowDrop(draggingNode, dropNode, type){
      if(draggingNode.parent.id === dropNode.parent.id){
        return true;
      }
    },
    /** 设备分类树提交按钮 */
    submitClassForm() {
      this.$refs["classForm"].validate(valid => {
        if (valid) {
          if (this.classForm.id != null) {
            updateDouyinClass(this.classForm).then(response => {
              this.msgSuccess("修改成功");
              this.open2 = false;
              this.getTreeList();
            });
          } else {
            addDouyinClass(this.classForm).then(response => {
              this.msgSuccess("新增成功");
              this.open2 = false;
              this.getTreeList();
            });
          }
        }
      });
    },
    /** 刷新设备分类树 */
    refreshClassTree(){
      this.getTreeList();
      this.queryParams.classId = null;
      this.checkTreeNode.pid = null;
      this.checkTreeNode.id = null;
      this.checkTreeNode.name = null;
      this.getList();
      this.single = true;
    },
  }
};
</script>
<style scoped>
/* .el-dialog__wrapper >>> .photo-dialog, .el-dialog__wrapper >>> .el-dialog__body{
  height: 90%;
} */
</style>
